package com.hxlc.service.handler;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.hxlc.model.ElementResp;
import com.hxlc.model.QueryParam;
import com.hxlc.model.QueryReq;
import com.hxlc.model.QueryResp;
import com.hxlc.pojo.EquipmentInfoDetailsEntity;
import com.hxlc.pojo.EquipmentInfoEntity;
import com.hxlc.util.CollectionUtils;
import com.hxlc.util.RectField;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import java.util.*;

/**
 * 设备处理
 */
@Component
@Slf4j
public class EquipmentHandler {

    @Value("${uyun.apiIp}")
    private String apiIp;

    @Value("${uyun.apikey}")
    private String apikey;

    @Value("${uyun.api.store.query}")
    private String apiQuery;


    public List<QueryResp> getQeryRespsByEquipmentInfos(List<EquipmentInfoEntity> equipmentInfoEntities, List<EquipmentInfoDetailsEntity> equipmentInfoDetailsList) {
        Map<String, EquipmentInfoEntity> equipmentInfoMap = RectField.conversionIndex(equipmentInfoEntities, "id");
        //设备详情
        Map<String, EquipmentInfoDetailsEntity> equipmentInfoDetailsMap = RectField.conversionIndex(equipmentInfoDetailsList, "metric");
        Map<String,List<String>> metricKeyIpsValue = new HashMap<>();
        equipmentInfoDetailsList.forEach(equipmentInfoDetailsEntity -> {
            List<String> ips = metricKeyIpsValue.get(equipmentInfoDetailsEntity.getMetric());
            if(ips == null){
                ips = new ArrayList<>();
                metricKeyIpsValue.put(equipmentInfoDetailsEntity.getMetric(),ips);
            }
            ips.add(equipmentInfoMap.get(equipmentInfoDetailsEntity.getEquipmentInfoId()).getIp());
        });
        Map<String,List<ElementResp>> ipKeyElementsValue = new HashMap<>();
        for(String metric : metricKeyIpsValue.keySet()){
            String baseApi = apiIp + apiQuery + apikey;
            QueryParam queryParam = new QueryParam();
            queryParam.setMetric(metric);
            queryParam.setStart(new Date().getTime() - 60*60*1000);
            queryParam.setEnd(new Date().getTime());
            Map<String,List<String>> map = new HashMap<>();
            map.put("ip",metricKeyIpsValue.get(metric));
            queryParam.setTags(map);
            queryParam.setGroup_by(new ArrayList<>(Arrays.asList("ip")));
            String postResultStr = null;
            List<QueryReq> queryReqs = new ArrayList<>();
            try {
                // TODO
//                postResultStr = httpService.getPostResultStr(baseApi, JSON.toJSONString(queryParam));
                HttpResponse response = HttpRequest.post(baseApi).body(JSON.toJSONString(queryParam)).execute();
                if (response.getStatus() == 200) {
                    postResultStr = response.body();
                    queryReqs = JSON.parseArray(postResultStr, QueryReq.class);
                } else {
                    log.error("OpenAPI error: url:{}", baseApi);
                }

            }catch (Exception e){
                e.printStackTrace();
                continue;
            }
            if(!CollectionUtils.isNotBlank(queryReqs)){
                continue;
            }
            EquipmentInfoDetailsEntity equipmentInfoDetail = equipmentInfoDetailsMap.get(metric);
            queryReqs.forEach(queryReq -> {
                String ip = queryReq.getGroup().get("ip");
                List<ElementResp> elementResps = ipKeyElementsValue.get(ip);
                if(elementResps == null){
                    elementResps = new ArrayList<>();
                    ipKeyElementsValue.put(ip,elementResps);
                }
                LinkedHashMap<String, String> points = queryReq.getPoints();
                Map.Entry<String, String> tail = CollectionUtils.getTail(points);
                if(tail == null){
                    return;
                }
                ElementResp elementResp = new ElementResp();
                elementResp.setLabel(equipmentInfoDetail.getLabel());
                elementResp.setValue(tail.getValue() + equipmentInfoDetail.getUnit());
                elementResps.add(elementResp);
            });
        }
        List<QueryResp> queryResps = new ArrayList<>();
        for(String ip : ipKeyElementsValue.keySet()){
            if(ip == null){
                continue;
            }
            QueryResp queryResp = new QueryResp();
            queryResp.setIp(ip);
            queryResp.setElementResps(ipKeyElementsValue.get(ip));
            queryResps.add(queryResp);
        }
        return queryResps;
    }
}
